package com.haidada.tk.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * web通用工具
 */
public final class WebUtils {
	private final static Logger log = LoggerFactory.getLogger(WebUtils.class);

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return servletRequestAttributes.getRequest();
	}

	public static HttpServletResponse getResponse() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return servletRequestAttributes.getResponse();
	}

	public static Object getAttributeFromRequest(String key) {
		return getRequest().getAttribute(key);
	}

	public static String getAttributeFromHeader(String key) {
		return getRequest().getHeader(key);
	}

	public static void writeJson(Object obj) {
		HttpServletResponse res = getResponse();
		res.setContentType("application/json;charset=utf-8");
		try {
			res.getWriter().write(JacksonUtils.toJson(obj));
			res.getWriter().flush();
			res.getWriter().close();
			return;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static void writeText(String text) {
		HttpServletResponse res = getResponse();
		res.setContentType("text/plain;charset=utf-8");
		try {
			res.getWriter().write(text);
			res.getWriter().flush();
			res.getWriter().close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	static final String PRE = "Bearer ";



	public static String getIp() {
		HttpServletRequest request = WebUtils.getRequest();
		String ip = request.getHeader("x-forwarded-for");

		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			if( ip.indexOf(",")!=-1 ){
				ip = ip.split(",")[0];
			}
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		log.info("获取客户端ip = {}", ip);
		return ip;
	}


}